package cn.com.hfuu;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
 
import java.io.IOException;
import java.util.Random;

 

 
/**
 * 产生随机验证码
 * @author git
 *
 */
public class VcodeUtil {

	private int w=70;
	private int h=45;
	private Color bgcolor=new Color(240,240,240);
	private Random radom=new Random();
	private StringBuilder code=new StringBuilder(4);
	
	public BufferedImage createImg(){
		//创建图片
		BufferedImage img=new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		//设置背景颜色
		img.getGraphics().setColor(bgcolor);
		img.getGraphics().fillRect(0, 0, w, h);
		
		return img;
	}
	
	//随机颜色
	public Color radomColor(){
		int r=radom.nextInt(256);
		int g=radom.nextInt(256);
		int b=radom.nextInt(256);
		return new Color(r,g,b);
	}
	
	String[] fontnames={"华文楷体","宋体","楷体","黑体","华文新魏","华文隶书","微软雅黑","楷体"};
	//随机字体
	public Font radomFont(){
		
		String name=fontnames[radom.nextInt(8)];
		int style=radom.nextInt(4);
		int size=radom.nextInt(5)+26;
		return new Font(name,style,size);
		
	}
	
	//随机字符
	public String radomChar(){
		String imgchar="0123456789";
		return imgchar.charAt(radom.nextInt(imgchar.length()))+"";
		
	}
	
	//画干扰线
	public void drawline(BufferedImage img){
		Graphics2D g=(Graphics2D) img.getGraphics();
		g.setColor(Color.BLACK);
		g.setStroke(new BasicStroke(1.5F));
		for (int i = 0; i < 2; i++) {
			int x1=radom.nextInt(w);
			int y1=radom.nextInt(h);
			int x2=radom.nextInt(w);
			int y2=radom.nextInt(h);
			g.drawLine(x1, y1, x2, y2);
		}
	}
	
	public BufferedImage getimg() throws FileNotFoundException, IOException{
		BufferedImage img=createImg();
		Graphics g=img.getGraphics();
		//字体、字符、颜色随机
		for (int i = 0; i < 4; i++) {
			String ch=radomChar();
			code.append(ch);
			g.setColor(radomColor());
			g.setFont(radomFont());
			if(i==1){
				g.drawString(ch, (int) ((w-4)/4*i+2), h-5);
			}else if(i==4){
				g.drawString(ch, (int) ((w-4)/4*i-2), h-5);
			}else{
				g.drawString(ch, (int) ((w-4)/4*i), h-5);
			}
			
		}
		drawline(img);
		//ImageIO.write(img, "JPEG", new FileOutputStream("E:\\a.jpg"));
		return img;
	}
	
	public String getCode(){
		return code.toString();
	}
}
